const {
  login,
  register,
  get_u,
  update_u,
  del_u,
  add_u
} = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
var express = require("express");
var router = express.Router();
const jwt = require("jsonwebtoken");
const loginCheck = require("../middleware/loginCheck");


/* GET users listing. */
router.post("/login", function (req, res, next) {
  const { user_email, user_pwd } = req.body;
  const result = login(user_email, user_pwd);

  return result.then((userData) => {
    if (userData.user_email) {
      const token = jwt.sign(
        {
          id: userData.user_id,
        },
        "#mongo_dect"
      );
      userData.token = token;
      res.json(new SuccessModel(userData));
      return;
    }
    res.json(new ErrorModel("登录失败"));
  });
});

router.post("/register", function (req, res, next) {
  const result = add_u(req.body);
  return result.then((val) => {
    if (val) {
      res.json(new SuccessModel(val));
    }else{
      res.json(new ErrorModel("注册失败"));
    }
  });
});


router.post("/add_u", function (req, res, next) {
  const result = add_u(req.body);
  return result.then((val) => {
    if (val) {
      res.json(new SuccessModel(val));
    } else {
      res.json(new ErrorModel("注册失败"));
    }
  });
});
router.get("/get_u", function (req, res, next) {
  const result = get_u();
  return result.then((val) => {
    res.json(new SuccessModel(val));
  });
});

router.post("/update_u", function (req, res, next) {
  const result = update_u(req.query.id, req.body);
  return result.then((val) => {
    if (val) {
      res.json(new SuccessModel());
    } else {
      res.json(new ErrorModel("更新失败"));
    }
  });
});

router.get("/del_u", (req, res, next) => {
  const result = del_u(req.query.id);
  return result.then((val) => {
    if (val) {
      res.json(new SuccessModel(val));
    } else {
      res.json(new ErrorModel("删除失败"));
    }
  });
});

module.exports = router;
